package com.windchime.blog.controller.admin;

import cn.hutool.crypto.SecureUtil;
import com.windchime.blog.entity.Admin;
import com.windchime.blog.result.R;
import com.windchime.blog.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * 登录
 * @author WindChime
 * @since 2021-07-31
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @param session session域
     * @return admin
     */
    @PostMapping("/login")
    public R login(String username, String password, HttpSession session) {

        Admin admin = adminService.getAdminByUsernameAndPassword(username, password);
        if (!StringUtils.isEmpty(admin)) {
            admin.setPassword("");
            session.setAttribute("admin", admin.getUsername());
            return R.ok().msg("登录成功").count(1L).data("admin", admin);
        } else {
            return R.error().msg("登录失败");
        }

    }

    /**
     * 注销方法
     * @param session session域
     */
    @PostMapping("/logout")
    public void logout(HttpSession session) {
        session.removeAttribute("admin");
    }

    /**
     * 修改管理员密码
     * @param id 管理员ID
     * @param old_password 老密码
     * @param new_password 新密码
     * @return true
     */
    @PostMapping("/edit-password")
    public R editPassword(Integer id, String old_password, String new_password) {
        Admin old_admin = adminService.getAdminByIdAndPassword(id, old_password);

        Admin new_admin = new Admin();
        if (!StringUtils.isEmpty(old_admin)) {
            BeanUtils.copyProperties(old_admin, new_admin);
            new_admin.setPassword(SecureUtil.md5(new_password));
            adminService.updateById(new_admin);
            return R.ok().msg("修改成功");
        } else {
            return R.error().msg("旧密码输入错误!请重新输入!");
        }
    }

}

